package bank.driver.servlet;

import java.io.IOException;
import java.net.URLEncoder;

import bank.Account;
import bank.InactiveException;
import bank.OverdrawException;

public class AccountProxy implements Account {
	
	String owner;
	String number;
	BankProxy bank;

	public AccountProxy(String owner, String number, BankProxy bank) {
		this.owner = owner;
		this.number = number;
		this.bank = bank;
	}

	@Override
	public void deposit(double amount) throws IOException,
			IllegalArgumentException, InactiveException {
		String param = this.bank.makeRequest("deposit?number=" + URLEncoder.encode(this.number, "UTF-8") + 
				       						    "&amount=" + URLEncoder.encode(Double.toString(amount), "UTF-8"));
		if ("ok".equals(param)){
			//do nothing
		} else if ("IllegalArgumentException".equals(param)){
			throw new IllegalArgumentException();
		} else if ("InactiveException".equals(param)){
			throw new InactiveException();
		}
	}

	@Override
	public double getBalance() throws IOException {
		String balance = this.bank.makeRequest("getBalance?number=" + URLEncoder.encode(this.number, "UTF-8"));
		return Double.valueOf(balance);
	}

	@Override
	public String getNumber() throws IOException {
		return this.number;
	}

	@Override
	public String getOwner() throws IOException {
		return this.owner;
	}

	@Override
	public boolean isActive() throws IOException {
		String active = this.bank.makeRequest("isActive?number=" + URLEncoder.encode(this.number, "UTF-8"));
		return Boolean.valueOf(active);
	}

	@Override
	public void withdraw(double amount) throws IOException,
			IllegalArgumentException, OverdrawException, InactiveException {
		String param = this.bank.makeRequest("withdraw?number=" + URLEncoder.encode(this.number, "UTF-8") + 
											 "&amount=" + URLEncoder.encode(Double.toString(amount), "UTF-8"));
		if("ok".equals(param)){
			//do nothing
		} else if ("IllegalArgumentException".equals(param)){
			throw new IllegalArgumentException();
		} else if ("OverdrawException".equals(param)){
			throw new OverdrawException();
		} else if ("InactiveException".equals(param)){
			throw new InactiveException();
		}
	}

}
